import os, os.path, sys
from PyQt4 import QtGui, QtCore
import image_editor_widget_base
import lucid.core
import lucid.plugins.fc_editor.fc_editors as fc_editors
import osg2
from pydispatch import dispatcher

class ImageEditorPlugin(lucid.core.IFcEditorPlugin):
   """ Viewer that displays an editor panel for images."""
   def __init__(self):
      super(ImageEditorPlugin, self).__init__()
      self.mImage = None
      self.widget = ImageEditorWidget(self)
      
      self.widget.connect(self.widget.mFileOpenButton, QtCore.SIGNAL("pressed()"), self.onFileOpen)
      

   @staticmethod
   def getName():
      return "Transform Core Editor"
      
   @staticmethod
   def getSupportedFcTypes():
      """ Return the type(s) that we support editing. """
      return [osg2.Image, ]
   
   def getEditorWidget(self):
      return self.widget

   def setFieldContainer(self, fc):
      assert type(fc) == osg2.Image
      self.mImage = fc
      self.widget.setFieldContainer(fc)
      
   # Controller methods
   def onFileOpen(self):
      # XXX: Get the suffix list from the file handler
      fileName = QtGui.QFileDialog.getOpenFileName(self.widget,
                       "Open Image...",
                        os.getcwd(),
                        "All Files (*)")
      
      if not fileName.isEmpty():
         fileName = str(fileName)
         loaded = self.mImage.read(fileName)
         if not loaded:
            QtGui.QMessageBox.critical(self.widget, "Load image failed.",
               "Failed to load image: [%s]"%fileName,
               QtGui.QMessageBox.Ignore|QtGui.QMessageBox.Default|QtGui.QMessageBox.Escape,
               QtGui.QMessageBox.NoButton, QtGui.QMessageBox.NoButton)
      
      self.widget.updateView()


class ImageEditorWidget(QtGui.QWidget, image_editor_widget_base.Ui_Form):
   """ Simple container widget. """
   def __init__(self, plugin, parent=None):
      QtGui.QWidget.__init__(self, parent)
      self.plugin = plugin
      self.setupUi(self)
      #self.updateView()

   def setupUi(self, Form):
      image_editor_widget_base.Ui_Form.setupUi(self,Form)
      self.mGenericEditor = fc_editors.GenericFcEditorWidget(self.splitter)
      self.mEditFrame.setParent(None)      
   
   def setFieldContainer(self, fc):
      self.mImage = fc
      self.mGenericEditor.setFieldContainer(fc)
      self.updateView()
   
   def updateView(self):
      # Set the filename area
      filename = self.mImage.getName()
      self.mFilenameEdit.setText(filename)
      
      
